<?php
namespace juven\libs {
    \defined( '_JEXEC' ) or die( 'Restricted access' );
    
    abstract class Controller {
        const EVENT_onControllerRun                         = "event_onControllerRun";
        const EVENT_onError_ModelFileNotFoundOrNotReadable  = "event_onError_ModelFileNotFoundOrNotReadable";
        
        protected $_className                  = \NULL;
        protected $_childClass                 = \NULL;
        protected $_unPrefixedControllerName   = \NULL;
        protected $_requestedActionName        = \NULL;
        protected $_requestedActionParams      = \NULL;
        public    $model                       = \NULL;
        
        /** @var View */
        public    $view                        = \NULL;
        
        abstract protected function _init();
        final public function __construct($requestedActionName=\NULL, $requestedActionParams=\NULL) {
            $this->_className               = __CLASS__;
            $this->_childClass              = \get_called_class();
            $this->_unPrefixedControllerName= \substr($this->_childClass, (\strpos($this->_childClass, "\ctrl_")+6));
            $this->_requestedActionName     = $requestedActionName;
            $this->_requestedActionParams   = $requestedActionParams;
            
            $dtp = new \stdClass();
            $dtp->className                 = $this->_className;
            $dtp->childClass                = $this->_childClass;
            $dtp->unPrefixedControllerName  = $this->_unPrefixedControllerName;
            $dtp->requestedActionName       = $this->_requestedActionName;
            $dtp->requestedActionParams     = $this->_requestedActionParams;
            
            juven::eventsManager()->publish(self::EVENT_onControllerRun, $dtp);
            
            $this->view     = new View();
//            $this->model    = $this->loadModel($this->_unPrefixedControllerName);
            $this->_init();
        }

        /**
         *  Loads the Model specified in $name and returns it as new object
         * @param string $name The model name
         * @return Model|NULL Returns the model object or NULL if model file was not found in the predefined filesystem path, or file is not readable
         */
        final public function loadModel($name) {
                $modelFile = juven::config()->modelsFolderPath.$name.'.php';
                if (!\is_readable($modelFile)){
                    juven::eventsManager()->publish(self::EVENT_onError_ModelFileNotFoundOrNotReadable, $modelFile);
                    return \NULL;
                }
                $cls = "juven\\models\\$name";
                return new $cls();
        }
        
        final public function unPrefixActionName($actionName){
            return \substr($actionName, (\strpos($actionName, "action_")+7));
        }
        
        final public function __destruct() { }
    }
}
?>
